﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using Infrastructure;
using MSIACCSL2.Web.CostCenterServices;
using MSIACCSL2.Web.CustomerServices;
using MSIACCSL2.Web.DepartemenServices;
using MSIACCSL2.Web.WarehouseServices;
using System.IO;
using WcfService1.DTO;

namespace MSIACCSL2.Web.ReportPage
{
    public partial class ReportSI : System.Web.UI.Page
    {
        private DataAccess<Object> DA;
        private ReportDocument SalesInvoiceSummary;
        private ReportDocument SalesInvoiceDetail;
        private CostCenterServices.CostCenterServicesClient costCenterClient;
        private string Tipe;

        public ReportSI()
        {
            DA = new DataAccess<object>();
            SalesInvoiceSummary = new ReportDocument();
            SalesInvoiceDetail = new ReportDocument();
            costCenterClient = new CostCenterServicesClient();
        } 

        protected void Page_Load(object sender, EventArgs e)
        {
                if (! IsPostBack)
                   Prepare();

                if (rblType.SelectedValue == "Summary")
                {
                    LoadReportSummary(DateTime.Parse(txtTgl1.Text, new CultureInfo("ID-id")), DateTime.Parse(txtTgl2.Text, new CultureInfo("ID-id")), listCostCenter.SelectedValue);
                }
                else if (! string.IsNullOrEmpty(txtTgl1.Text) && ! string.IsNullOrEmpty(txtTgl2.Text))
                {
                    LoadReport(DateTime.Parse(txtTgl1.Text, new CultureInfo("ID-id")), DateTime.Parse(txtTgl2.Text, new CultureInfo("ID-id")));
                }
              

        }


       void Prepare()
       {
           LoadCostCenter();
           LoadDepartemen();
           LoadSubgroup();
           LoadGroup();
           LoadItem();
       }


        void LoadCostCenter()
        {
            var costCenters = costCenterClient.GetAllCostCenter().ToList();
            costCenters.Insert(0,new CostCenterDTO());
            foreach (var costCenter in costCenters)
            {
                ListItem li = new ListItem(costCenter.Description,costCenter.CostCenterId);
                listCostCenter.Items.Add(li);
            }
        }

        void LoadDepartemen()
        {
            var departemenClient = new DepartemenServicesClient();
            var departemens =  departemenClient.GetAllDepartemen().ToList();
            departemens.Insert(0,new DepartemenDTO());
            foreach (var departemenDto in departemens)
            {
                var li = new ListItem(departemenDto.Name, departemenDto.Code);
                listDepartemen.Items.Add(li);
            }
            
        }

        void LoadCustomer(string customerName)
        {
            var customerClient = new CustomerServicesClient();
            var customers = customerClient.GetCustomerList(customerName).ToList();
            customers.Insert(0,new CustomerDTO());
            foreach (var customerDto in customers)
            {
                var li = new ListItem(customerDto.CustomerName, customerDto.CustomerId);
                listCustomer.Items.Add(li);
            }
        }


        void LoadGroup ()
        {
            var groupClient = new GroupServices.GroupServicesClient();
            var groups = groupClient.GetAll().ToList();
            groups.Insert(0,new GroupDTO());
            foreach (var groupDto in groups)
            {
                var li = new ListItem(groupDto.GroupName, groupDto.GroupID);
                listGroup.Items.Add(li);
            }
        }

        void LoadSubgroup()
        {
            var subgroupClient = new SubgroupServices.SubGroupServiceClient();
            var subgroups = subgroupClient.GetAllSubGroup().ToList();
            subgroups.Insert(0,new SubGroupDTO());
            foreach (var subgroup in subgroups)
            {
                var li = new ListItem(subgroup.SubGroupName, subgroup.SubGroupID);
                listSubgroup.Items.Add(li);

            }
           
        }

        void LoadItem()
        {
            var itemClient = new ItemServices.ItemServicesClient();
            var items = itemClient.GetAllItem().ToList();
            items.Insert(0,new ItemDTO());
            foreach (var itemDto in items)
            {
                var li = new ListItem(itemDto.ItemName, itemDto.ItemId);
                listItem.Items.Add(li);
            }
        }


       
      
    
        protected void Button1_Click(object sender, EventArgs e)
        {

        }

   

        public void LoadReportSummary(DateTime tglStart,DateTime tglEnd,string costCenter)
        {
            StringBuilder sql = new StringBuilder();
            using (StreamReader sr = File.OpenText(Server.MapPath("~/sql/ReportSIHeader.txt")))
            {
                String str = string.Empty;
                while ((str = sr.ReadLine()) != null)
                    sql.Append(str);
            }

            sql.AppendFormat(" where si.InvoiceDate>='{0}' AND si.InvoiceDate<='{1}'", tglStart.ToString("yyyy-MM-dd"),
                             tglEnd.ToString("yyyy-MM-dd"));
            if (!string.IsNullOrEmpty(costCenter))
                sql.AppendFormat(" AND SI.CostCenterId='{0}'", costCenter);

            var Source = DA.GetDataListDataSet(sql.ToString());
            string reportPath = Server.MapPath("~/Report/LapSISummary.rpt");
            SalesInvoiceSummary.Load(reportPath);
            SalesInvoiceSummary.SetDataSource(Source.Tables[0]);
            SetupParameter(tglStart, tglEnd, SalesInvoiceSummary);
            CrystalReportViewer1.ReportSource = SalesInvoiceSummary;
            CrystalReportViewer1.PrintMode = CrystalDecisions.Web.PrintMode.ActiveX;
        }


        public void LoadReport(DateTime tglStart, DateTime tglEnd)
        {
            StringBuilder sql = new StringBuilder();
            using (StreamReader sr = File.OpenText(Server.MapPath("~/sql/ReportSIDetail.txt")))
            {
                String str = string.Empty;
                while ((str = sr.ReadLine()) != null)
                    sql.Append(str);
            }

            sql.AppendFormat(" where si.InvoiceDate>='{0}' AND si.InvoiceDate<='{1}'", tglStart.ToString("yyyy-MM-dd"),
                             tglEnd.ToString("yyyy-MM-dd"));

            if (listCostCenter.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
                sql.Append(" AND SI.CostCenterID in (");
            foreach (var group in listCostCenter.Items.Cast<ListItem>().Where(x => x.Selected && !string.IsNullOrEmpty(x.Value)))
                sql.AppendFormat("'{0}',", group.Value);
            if (listCostCenter.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
            {
                sql.Remove(sql.Length - 1, 1);
                sql.Append(")");
            }


            if (listDepartemen.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
                sql.Append(" AND cc.CodeDepartemen in (");
            foreach (var group in listDepartemen.Items.Cast<ListItem>().Where(x => x.Selected && !string.IsNullOrEmpty(x.Value)))
                sql.AppendFormat("'{0}',", group.Value);
            if (listDepartemen.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
            {
                sql.Remove(sql.Length - 1, 1);
                sql.Append(")");
            }

            if (listGroup.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
                sql.Append(" AND g.GroupID in (");
            foreach (var group in listGroup.Items.Cast<ListItem>().Where(x => x.Selected && !string.IsNullOrEmpty(x.Value)))
                sql.AppendFormat("'{0}',", group.Value);
            if (listGroup.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
            {
                sql.Remove(sql.Length - 1, 1);
                sql.Append(")");
            }

            if (listSubgroup.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
                sql.Append(" AND sg.SubgroupID in (");
            foreach (var group in listSubgroup.Items.Cast<ListItem>().Where(x => x.Selected && !string.IsNullOrEmpty(x.Value)))
                sql.AppendFormat("'{0}',", group.Value);
            if (listSubgroup.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
            {
                sql.Remove(sql.Length - 1, 1);
                sql.Append(")");
            }

            if (listItem.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
                sql.Append(" AND i2.ItemID in (");
            foreach (var group in listItem.Items.Cast<ListItem>().Where(x => x.Selected && !string.IsNullOrEmpty(x.Value)))
                sql.AppendFormat("'{0}',", group.Value);
            if (listItem.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
            {
                sql.Remove(sql.Length - 1, 1);
                sql.Append(")");
            }

            var source = DA.GetDataListDataSet(sql.ToString());
            string reportPath;

            if (rblType.SelectedValue == "No.Invoice")
            {
              reportPath= Server.MapPath("~/Report/ReportSIBySINO.rpt");
            }
            else if (rblType.SelectedValue == "Barang")
            {
                reportPath = Server.MapPath("~/Report/ReportSIBySIBarang.rpt");
            }else
            {
                reportPath = Server.MapPath("~/Report/ReportSIBySINO+Barang.rpt");
            }
            
            SalesInvoiceDetail.Load(reportPath);
            SalesInvoiceDetail.SetDataSource(source.Tables[0]);
            SetupParameter(tglStart,tglEnd,SalesInvoiceDetail);
            SetParameter();
            CrystalReportViewer1.ReportSource = SalesInvoiceDetail;
            CrystalReportViewer1.PrintMode = CrystalDecisions.Web.PrintMode.ActiveX;
        }


        private void SetupParameter(DateTime tglStart, DateTime tglEnd, ReportDocument reportDocument)
        {
            var param = new ParameterDiscreteValue();
            param.Value = tglStart.ToString("dd-MM-yyyy");
            var paramValue = new ParameterValues();
            paramValue.Add(param);
            reportDocument.DataDefinition.ParameterFields["tglawal"].ApplyCurrentValues(paramValue);
            var param2 = new ParameterDiscreteValue();
            param2.Value = tglEnd.ToString("dd-MM-yyyy");
            var paramValue2 = new ParameterValues();
            paramValue2.Add(param2);
            reportDocument.DataDefinition.ParameterFields["tglakhir"].ApplyCurrentValues(paramValue2);
        }


        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
            this.Unload += Page_Unload;
        }

        void Page_Unload(object sender, EventArgs e)
        {
            SalesInvoiceSummary.Clone();
            SalesInvoiceSummary.Dispose();

            SalesInvoiceDetail.Clone();
            SalesInvoiceDetail.Dispose();
        }

        protected void txtCustomerName_TextChanged(object sender, EventArgs e)
        {
            LoadCustomer(txtCustomerName.Text.Trim());
        }

        protected void rblType_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void SetParameter()
        {
            var param = new ParameterDiscreteValue();
            param.Value = txtTgl1.Text;
            var paramValue = new ParameterValues();
            paramValue.Add(param);
            SalesInvoiceDetail.DataDefinition.ParameterFields["tglawal"].ApplyCurrentValues(paramValue);

            param = new ParameterDiscreteValue();
            param.Value = txtTgl2.Text;
            paramValue = new ParameterValues();
            paramValue.Add(param);
            SalesInvoiceDetail.DataDefinition.ParameterFields["tglakhir"].ApplyCurrentValues(paramValue);

            param = new ParameterDiscreteValue();
            param.Value = listCostCenter.SelectedValue;
            paramValue = new ParameterValues();
            paramValue.Add(param);
            SalesInvoiceDetail.DataDefinition.ParameterFields["CostCenter"].ApplyCurrentValues(paramValue);

            param = new ParameterDiscreteValue();
            param.Value = listDepartemen.SelectedValue;
            paramValue = new ParameterValues();
            paramValue.Add(param);
            SalesInvoiceDetail.DataDefinition.ParameterFields["Departemen"].ApplyCurrentValues(paramValue);

            param = new ParameterDiscreteValue();
            param.Value = rblGroup.SelectedValue;
            paramValue = new ParameterValues();
            paramValue.Add(param);
            SalesInvoiceDetail.DataDefinition.ParameterFields["grouptype"].ApplyCurrentValues(paramValue);
        }


    }
}